﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint.ApplicationRuntime;
using VH.SharePoint.Api.Helpers;

namespace VH.SharePoint.Api.HttpModules
{
    public class WeblogUrlRewriter : IHttpModule
    {
        private const string defaultSPWeblogPath = "/_layouts/metaweblog.aspx";
        private const string defaultWLWManifestPath = "/wlwmanifest.xml";
        private const string defaultListAsmxPath = "/_vti_bin/lists.asmx";
        public void Init(HttpApplication context)
        {
            context.BeginRequest += ContextOnBeginRequest;
        }

        private void ContextOnBeginRequest(object sender, EventArgs eventArgs)
        {
            var application = (HttpApplication)sender;
            
            RewriteUrl(application, defaultSPWeblogPath, SPConstants.EndPointApi);
            RewriteUrl(application, defaultWLWManifestPath, SPConstants.EndPointWlwManifest);

            var request = application.Context.Request;
            if (WlwHelper.IsRequestedByWlw(application.Context) && request.ContentType.StartsWith("text/xml", StringComparison.InvariantCultureIgnoreCase))
            {
                RewriteUrl(application, defaultListAsmxPath, SPConstants.EndPointWlw);
            }

        }

        private void RewriteUrl(HttpApplication application, String defaultPath, String newPath)
        {
            var filePath = application.Context.Request.FilePath.ToLowerInvariant();
            if (filePath.EndsWith(defaultPath, StringComparison.InvariantCultureIgnoreCase))
            {
                var targetUrl = filePath.Replace(defaultPath, newPath);
                /*var index = targetUrl.IndexOf("/_vti_bin", System.StringComparison.Ordinal);
                if(index !=-1 )
                    targetUrl = targetUrl.Substring(index);
                index = targetUrl.IndexOf("/_layouts", System.StringComparison.Ordinal);
                if (index != -1)
                    targetUrl = targetUrl.Substring(index);*/
                application.Context.RewritePath(targetUrl);
                var module = application.Modules["SPRequestModule"] as SPRequestModule;
                module.BeginRequestHandler(application, new EventArgs());
                application.Response.Headers.Remove("SPRequestGuid");
                //application.Context.RewritePath(targetUrl, string.Empty, string.Empty, true);
                //application.Context.RemapHandler(System.Web.UI.PageParser.GetCompiledPageInstance(targetUrl, application.Context.Server.MapPath(targetUrl), application.Context));
            }
        }

        public void Dispose()
        {
            
        }
    }
}
